﻿using UnityEngine;
using System.Collections;

public class VictoryDetection : MonoBehaviour, IResettable {

    public float radiusOfSatisfaction = 1.0f;
    private float radiusOfSatisfactionSquared = 1.0f;
    private bool victoryDetected = false;

    GameObject[] targets;

    public bool VictoryDetected { get { return victoryDetected; } }

	// Use this for initialization
	void Start () {
        targets = GameObject.FindGameObjectsWithTag("target");
        radiusOfSatisfactionSquared = radiusOfSatisfaction * radiusOfSatisfaction;
        ResetItemList.Instance.AddItem(this);
	}
	
	// Update is called once per frame
	void Update () {

        if (victoryDetected) return;

        foreach (GameObject target in targets)
        {

            if ((this.transform.position - target.transform.position).sqrMagnitude < radiusOfSatisfactionSquared)
            {
                victoryDetected = true;

                GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
                foreach (GameObject enemy in enemies)
                {
                    EnemyManager manager = enemy.GetComponent<EnemyManager>();
                    manager.OnPlayerVictory();
                }

                //Vector3 meToTarget = target.transform.position - transform.position;
                //RaycastHit losHit;
                //Ray losCheck = new Ray(this.transform.position, meToTarget);
                //if (Physics.Raycast(losCheck, out losHit, meToTarget.magnitude))
                //{
                //    if (losHit.collider.tag == "target")
                //    {
                //        victoryDetected = true;
                //        print("Victory detected!");
                //    }
                //}
                //else
                //{
                //    print("Player is close enough but target cannot see player");
                //}
            }
        }
	}

    public void Reset()
    {
        victoryDetected = false;
    }

    public bool PersistAfterReset()
    {
        return true;
    }
}
